<template>
  <div style="border: black 0px solid;width: 100%;height: 550px;display: flex;
flex-direction: column;
align-items: center;">
    <!--    按钮栏    -->
    <div class="awsCenter" style="width: 100%;height: 40px;border: black 0px solid">
      <el-input style="width: 150px;margin-right: 10px" placeholder="胎位描述" v-model="baySelectForm.bay_description"></el-input>
      <el-input style="width: 150px;margin-right: 10px" placeholder="船号" v-model="baySelectForm.ship_number"></el-input>

      <el-button @click="getBayList" style="width: 80px;margin-left: 10px" type="primary" plain>查询</el-button>
      <el-button @click="bayRefresh" style="margin-left: 10px" type="primary" circle><el-icon><refresh /></el-icon></el-button>
      <div style="margin-left: auto">
        <el-button style="width: 80px;" type="primary" @click="showBay=true;bayFlag='new';bayTitle='新增调度信息';cleanBayForm();">新增</el-button>
        <el-button style="margin-left: 0px" @click="confDelete">批量删除</el-button>
        <ImportExcelButton style="margin-left: 20px" :fields="importFields" @import-data="handleImportData" />
      </div>

    </div>

    <!--   表格    -->
    <el-table :data="bayList" stripe style="width: 100%;margin-top: 20px" @selection-change="selectClient">
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column prop="bay_description" label="胎位描述" width="120" />
      <el-table-column prop="bay_number" label="胎位编号" width="150" />
      <el-table-column prop="bay_length" label="分段长（m）" width="150px" />
      <el-table-column prop="bay_width" label="分段宽（m）" width="150px"/>
      <el-table-column prop="labor_team" label="劳务队" width="100px"/>
      <el-table-column prop="ship_number" label="船号" width="100px"/>
      <el-table-column prop="planned_start_time" label="计划开始时间" width="150px">
        <template #default="{ row }">
          {{formatDate(row.planned_start_time)}}
        </template>
      </el-table-column>
      <el-table-column prop="planned_end_time" label="计划结束时间" width="150px">
        <template #default="{ row }">
          {{formatDate(row.planned_end_time)}}
        </template>
      </el-table-column>
      <el-table-column prop="latest_end_time" label="最晚完工时间" width="150px">
        <template #default="{ row }">
          {{formatDate(row.latest_end_time)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="primary" plain :icon="Edit" circle @click="showBay=true;bayFlag='edit';bayTitle='修改调度信息';showBayData(row)" />
          <el-button type="danger" plain :icon="Delete" circle @click="handleClientDelete(row)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <div  class="demo-pagination-block">
      <el-pagination
        style="margin-top: 20px"
        v-model:current-page="currentPage"
        :page-size="8"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>


  <el-dialog
    v-model="showBay"
    :title="bayTitle"
    width="600px"
    align-center
    style="height: 520px;"
    draggable
    :close-on-click-modal="false"
  >
    <div style="padding: 20px; height: 400px; overflow-y: auto">
      <el-form :model="bayForm" label-position="top" ref="bayFormRef" label-width="120px">
        <el-row :gutter="20">
          <!-- 左侧表单项 -->
          <el-col :span="12">
            <el-form-item prop="ship_number" label="船号">
              <el-input v-model="bayForm.ship_number" placeholder="请输入船号" />
            </el-form-item>

            <el-form-item prop="segment_number" label="分段号">
              <el-input v-model="bayForm.segment_number" placeholder="请输入分段号" />
            </el-form-item>

            <el-form-item prop="bay_number" label="胎位编号">
              <el-input v-model="bayForm.bay_number" placeholder="请输入胎位编号" />
            </el-form-item>

            <el-form-item prop="labor_team" label="劳务队">
              <el-input v-model="bayForm.labor_team" placeholder="请输入劳务队名称/编号" />
            </el-form-item>
            <el-form-item label="最晚完工时间" prop="latest_end_time">
              <el-date-picker
                v-model="bayForm.latest_end_time"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 右侧表单项 -->
          <el-col :span="12">
            <el-form-item prop="bay_length" label="胎位长（m）">
              <el-input-number
                v-model="bayForm.bay_length"
                :precision="2"
                :step="0.1"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item prop="bay_width" label="胎位宽（m）">
              <el-input-number
                v-model="bayForm.bay_width"
                :precision="2"
                :step="0.1"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="计划开始时间" prop="planned_start_time">
              <el-date-picker
                v-model="bayForm.planned_start_time"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期时间"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="计划结束时间" prop="planned_end_time">
              <el-date-picker
                v-model="bayForm.planned_end_time"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="胎位描述" prop="bay_description">
          <el-input
            v-model="bayForm.bay_description"
            type="textarea"
            :rows="3"
            placeholder="请输入胎位描述信息"
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div style="margin-top: -20px">
        <el-button @click="showBay = false">取 消</el-button>
        <el-button type="primary" @click="baySaveOrUpdate">确 认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {getUserClientService,userRegisterService,deleteClientService,updateClientService} from '@/api/user.js'
import {ElMessage, ElMessageBox, UploadFile} from "element-plus";
const confDialog = ref(false)
import moment from 'moment';
import type { ComponentSize } from 'element-plus'
const currentPage = ref(1)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
import { Refresh } from '@element-plus/icons-vue';

import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
import {upload} from '@/api/upload.js'





const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = async (val: number) => {
  await getBayList(val)
}
import {
  Delete,
  Edit,
} from '@element-plus/icons-vue'
import {onMounted, ref, watch} from 'vue'
import type { TabsPaneContext } from 'element-plus'
const activeName = ref('size')

import {useUserStore} from "@/stores/user/user.js";
import { useRouter } from 'vue-router'
const userStore=useUserStore()
const router = useRouter();
onMounted(async ()=>{
  //分段尺寸信息查询
  await getBayList(1);

})





const tableData = ref([])

//查询
const total=ref(0)



const selectable = (row, index) => {
  // 在这里可以设置某些条件下的行是否可选
  if (row.username===userStore.user.username){
    return false;
  }
  return true;
};






const selected=ref([])
function selectClient(selectedRows) {
  console.log(selectedRows)
  selected.value=selectedRows
}


const confDelete=(()=>{
  if (selected.value.length===0){
    ElMessage.warning("请先选择数据")
  }else {
    ElMessageBox.confirm(
      '您确定要删除吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {


      deleteBay()


    }).catch((err) => {
      console.log(err)
    });
  }
})

//单个删除
const handleClientDelete=(async (row)=>{
  selected.value.push(row)
  console.log(row)
  ElMessageBox.confirm(
    '您确定要删除吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {

    deleteBay()


  }).catch((err) => {
    console.log(err)
  });
  //confDialog.value=true
})

//公用 ：删除确认框
const confDeleteDialog=(()=>{

  confDialog.value = false
})








import {
  addSegmentService,
  deleteSegmentsService,
  getSegmentsService,
  updateSegmentsService
} from '@/api/ship_segments.js'






const sizeSelectForm=ref({
  current:'',
  pageSize:8,
  ship_type:'',
  station_cycle:''
})
const shipSegmentsList=ref([])
const getSize=async (val)=>{
  sizeSelectForm.value.current=val
  let res=await getSegmentsService(sizeSelectForm.value)
  if (res.code===200){
    shipSegmentsList.value=res.data.list
    total.value=res.data.total
  }
}



const deleteSize=(async ()=>{
  await deleteSegmentsService(selected.value).then(res=>{
    if (res.code===200){
      ElMessage.success('删除成功')
      getSize(1)
    }
  })
  selected.value=[]
})


function formatDate(date) {
  if (!date) return '';

  const d = new Date(date);
  const year = d.getFullYear();
  const month = (d.getMonth() + 1).toString().padStart(2, '0');
  const day = d.getDate().toString().padStart(2, '0');

  return `${year}-${month}-${day}`;
}







//调度信息查询
import {
  addBayAssignedSegmentService,
  getBayAssignedSegmentsService,
  updateBayAssignedSegmentService,
  deleteBayAssignedSegmentService,
  batchDeleteBayAssignedSegmentsService, batchAddBayAssignedSegmentsService
} from '@/api/bay_assignment.js';
import ImageZoomViewer from "@/components/ImageZoomViewer.vue";
import ImportExcelButton from "@/components/ImportExcelButton.vue";

// 控制弹窗显示
const showBay = ref(false);
const bayFlag = ref('');  // 'new' 或 'edit'
const bayTitle = ref('');

// 表单数据
const bayForm = ref({
  assignment_id: '',
  bay_description: '',
  bay_number: '',
  bay_length: null,
  bay_width: null,
  labor_team: '',
  ship_number: '',
  segment_schedule_id: '',
  segment_number: '',
  planned_start_time: null,
  planned_end_time: null,
  latest_end_time: null
});
const importFields = Object.keys(bayForm.value).slice(1)
// 清空表单
const cleanBayForm = () => {
  bayForm.value = {
    assignment_id: '',
    bay_description: '',
    bay_number: '',
    bay_length: null,
    bay_width: null,
    labor_team: '',
    ship_number: '',
    segment_schedule_id: '',
    segment_number: '',
    planned_start_time: null,
    planned_end_time: null,
    latest_end_time: null
  };
};

// 保存或更新胎位分配信息
const baySaveOrUpdate = async () => {
  const data = bayForm.value;

  // 必填字段校验（根据业务需要调整）
  if (!data.ship_number || !data.segment_number || !data.bay_number || !data.bay_length || !data.bay_width) {
    ElMessage.warning("请填写带 * 的必填项");
    return;
  }

  try {
    let res;
    if (bayFlag.value === 'new') {
      res = await addBayAssignedSegmentService(data);
    } else {
      res = await updateBayAssignedSegmentService(data.assignment_id, data);
    }

    if (res.code === 200) {
      ElMessage.success(bayFlag.value === 'new' ? "新增成功" : "修改成功");
      showBay.value = false;
      await getBayList(1);  // 刷新列表
    }
  } catch (err) {
    ElMessage.error("保存失败，请重试");
    console.error(err);
  }
};

// 显示编辑数据
const showBayData = (row) => {
  bayForm.value = { ...row };
};

// 查询条件表单
const baySelectForm = ref({
  current: 1,
  pageSize: 8,
  ship_number: '',
  bay_description: ''
});

// 分页数据
const bayList = ref([]);

// 获取胎位分配信息列表
const getBayList = async (val) => {
  baySelectForm.value.current = val;
  const res = await getBayAssignedSegmentsService(baySelectForm.value);
  if (res.code === 200) {
    bayList.value = res.data.list;
    total.value = res.data.total;
  }
};

// 刷新查询
const bayRefresh = () => {
  baySelectForm.value.ship_number = '';
  baySelectForm.value.bay_description = '';
  getBayList(1);
};



const deleteBay = async () => {

  const res = await batchDeleteBayAssignedSegmentsService(selected.value);
  if (res.code === 200) {
    ElMessage.success(`成功删除 ${selected.value.length} 条记录`);
    await getBayList(1);
  }

  selected.value = [];
};

const images = ref([
  { date: '2025-06-01', url: '/imageData/2025-06-01.png' },
]);



const importedData = ref<any[]>([])

const handleImportData = async (data: any[]) => {
  console.log('导入的数据:', data)
  importedData.value = data
  const res = await batchAddBayAssignedSegmentsService(importedData.value)
  if (res.code === 200) {
    ElMessage.success(res.message)
    await getBayList(1)
  }
}

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
}
.demo-date-picker {
  display: flex;
  padding: 0;
  flex-wrap: wrap;
}
.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 0;
}
.demo-date-picker .block:last-child {
  border-right: none;
}
.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.awsCenter{
  display: flex;
  align-items: center;
}
</style>
